package org.come.control;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.Properties;

import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;

import org.come.Frame.RaceChangeMainJframe;
import org.come.Frame.ZhuFrame;
import org.come.Jpanel.ZhuJpanel;
import org.come.action.FromServerAction;
import org.come.bean.LoginResult;
import org.come.bean.RoleTransBean;
import org.come.mouslisten.PetAddPointMouslisten;
import org.come.until.CutButtonImage;
import org.come.until.FormsManagement;
import org.come.until.GoodsListFromServerUntil;
import org.come.until.GsonUtil;

import com.tool.image.ImageMixDeal;
import com.tool.role.RoleData;
import com.tool.role.RoleProperty;
/**
 * 登录信息
 * @author Administrator
 *
 */
public class RoleConversionControl implements FromServerAction {

	@Override
	public void controlMessFromServer(String mes, String type) {
		// 依据协议头进行划分方法
		RoleTransBean roleTransBean=GsonUtil.getGsonUtil().getgson().fromJson(mes, RoleTransBean.class);
		LoginResult loginResult = roleTransBean.getLoginResult();
		ImageIcon icon = CutButtonImage.getImage("img/head/s" + loginResult.getSpecies_id() + ".png", -1, -1);
		ZhuJpanel.getLabroleimg().setIcon(icon);
		RoleData.getRoleData().setPrivateData(roleTransBean.getPrivateData());
		RoleProperty.Resetgrade(loginResult.getGrade(), loginResult.getRace_id());
		RoleProperty.Resetborn(null, roleTransBean.getPrivateData().getBorn());
		loginResult.setHp(new BigDecimal(RoleProperty.getHp(loginResult)));
		loginResult.setMp(new BigDecimal(RoleProperty.getMp(loginResult)));
		RoleData.getRoleData().setLoginResult(loginResult);
		ImageMixDeal.userimg.getRoleShow().init(loginResult);
		ImageMixDeal.userimg.changeskin(null);
		PetAddPointMouslisten.getplayerValue();
		GoodsListFromServerUntil.GoodExpansion(loginResult.getAttachPack(),loginResult.getTurnAround());
		FormsManagement.HideForm(41);
		FormsManagement.HideForm(7);
		RaceChangeMainJframe.getRaceChangeMainJframe().getRaceChangeMainJpanel().cleanView();
		if (roleTransBean.getMounts()!=null) {
			ZhuJpanel.setListMount(roleTransBean.getMounts());
		}
		ZhuFrame.getZhuJpanel().clearHotkeySkill();

		// 转换后处理自定义头像，避免被默认头像覆盖，同时不弹出Teststatejframe窗口
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					// 更新角色配置文件中的种族ID
					String roleId = loginResult.getRole_id().toString();
					String newSpeciesId = loginResult.getSpecies_id().toString();
					Properties props = new Properties();
					File file = new File("resource/other/avatar_" + roleId + ".properties");

					// 如果存在旧的配置文件，先加载它
					if (file.exists()) {
						java.io.FileInputStream fis = new java.io.FileInputStream(file);
						props.load(fis);
						fis.close();

						// 获取保存的种族ID
						String savedSpeciesId = props.getProperty("speciesId", "");

						// 如果种族发生变化
						if (!savedSpeciesId.equals(newSpeciesId)) {
							// 更新种族ID
							props.setProperty("speciesId", newSpeciesId);

							// 检查是否有自定义头像设置
							String savedAvatarPath = props.getProperty("avatarPath", "");

							// 如果有自定义头像设置，检查该头像是否适用于新种族
							// 这里我们简单地清除旧的自定义头像设置，因为种族变了，旧头像可能不适用
							if (!savedAvatarPath.isEmpty()) {
								props.remove("avatarPath");
							}

							// 保存更新后的配置
							java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
							props.store(fos, "Avatar configuration updated after role conversion for role " + roleId);
							fos.close();

							// 使用新种族的默认头像
							ImageIcon newIcon = CutButtonImage.getImage("img/head/s" + newSpeciesId + ".png", 58, 58);
							ZhuJpanel.getLabroleimg().setIcon(newIcon);
						}
					} else {
						// 创建新的配置文件
						props.setProperty("speciesId", newSpeciesId);
						java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
						props.store(fos, "Avatar configuration for role " + roleId);
						fos.close();

						// 使用新种族的默认头像
						ImageIcon newIcon = CutButtonImage.getImage("img/head/s" + newSpeciesId + ".png", 58, 58);
						ZhuJpanel.getLabroleimg().setIcon(newIcon);
					}

					// 刷新AvatarSwitchFrame中的头像（如果窗口是打开的）
					refreshAvatarSwitchFrame();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 刷新头像切换窗口中的头像
	 */
	private void refreshAvatarSwitchFrame() {
		try {
			// 获取AvatarSwitchFrame实例并刷新头像
			// 如果AvatarSwitchFrame已经创建并且可见，则刷新它
			if (FormsManagement.getInternalForm2(199) != null) {
				org.come.model.InternalForm internalForm = FormsManagement.getInternalForm2(199);
				javax.swing.JInternalFrame avatarFrame = internalForm.getFrame();
				if (avatarFrame instanceof org.come.Jpanel.AvatarSwitchFrame) {
					((org.come.Jpanel.AvatarSwitchFrame) avatarFrame).refreshAvatars();
				}
			}
		} catch (Exception e) {
			// 忽略异常，因为AvatarSwitchFrame可能尚未创建
			e.printStackTrace();
		}
	}
}
